<script setup lang="ts">
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import { is_ios, isApp } from '@/utils/util';
import { useRouter } from 'vue-router';
import type { ConfigProviderThemeVars } from 'vant';
import { useNavBarHeight } from '@/composables/useNavBarHeight';

const { navBarHeight } = useNavBarHeight();

const props = withDefaults(
  defineProps<{
    rightText?: string;
    placeholder?: boolean;
    transparent?: boolean;
    textColor?: string;
    scrollEl?: string;
  }>(),
  {
    rightText: '',
    placeholder: true,
    transparent: false,
    textColor: '',
    scrollEl: '',
  }
);

const emit = defineEmits<{
  (e: 'onClickRight'): void;
}>();

// 定义路由
const router = useRouter();

// 状态栏高度
const getStatusBarHeight = () => {
  if (isApp() && !is_ios()) {
    return '35px';
  } else {
    return '0px';
  }
};
const statusBarHeight = ref(getStatusBarHeight());

// 是否为第一个页面
const isFirstPage = ref(history.state.position === 0);
router.afterEach(() => {
  isFirstPage.value = history.state.position === 0;
});

const handleBack = () => {
  if (isFirstPage.value) {
    try {
      // @ts-ignore
      window.flutter_inappwebview.callHandler('closePage', 'Hello from JavaScript!');
    } catch (err) {
      /** empty */
    }
  } else {
    router.back();
  }
};

const handleClickRight = () => {
  emit('onClickRight');
};

const getThemTextColor = () => {
  if (props.textColor) {
    return props.textColor;
  }
  return props.transparent ? '#ffffff' : '#000000';
};
const themeVars: ConfigProviderThemeVars = reactive({
  navBarHeight: `calc(46px + ${statusBarHeight.value})`,
  navBarIconColor: getThemTextColor(),
  navBarTextColor: getThemTextColor(),
  navBarTitleTextColor: getThemTextColor(),
  navBarBackground: props.transparent ? 'transparent' : 'var(--van-background-2)',
});

// 头部透明渐变控制
function interpolateColor(color1: number[], color2: number[], factor: number) {
  const result = color1.map((channel, i) => Math.round(channel + factor * (color2[i] - channel)));
  return `rgb(${result.join(',')})`;
}
function updateGradient(percentage: number) {
  const color1 = [255, 255, 255]; // #ffffff
  const color2 = [0, 0, 0]; // #000000

  const interpolatedColor = interpolateColor(color1, color2, percentage);
  return interpolatedColor;
}
function setTextColor(ratioOrColor: number | string) {
  if (props.textColor) {
    themeVars.navBarTitleTextColor = props.textColor;
    themeVars.navBarTextColor = props.textColor;
    themeVars.navBarIconColor = props.textColor;
  } else if (typeof ratioOrColor === 'string') {
    themeVars.navBarTitleTextColor = ratioOrColor;
    themeVars.navBarTextColor = ratioOrColor;
    themeVars.navBarIconColor = ratioOrColor;
  } else {
    const textColor = updateGradient(ratioOrColor);
    themeVars.navBarTitleTextColor = textColor;
    themeVars.navBarTextColor = textColor;
    themeVars.navBarIconColor = textColor;
  }
}

function pageScroll(e: any) {
  let scrollY = 0;
  if (props.scrollEl) {
    scrollY = e.target.scrollTop;
  } else {
    scrollY = window.scrollY || window.pageYOffset;
  }
  if (scrollY <= navBarHeight.value) {
    const ratio = scrollY / navBarHeight.value;
    setTextColor(ratio > 1 ? 1 : ratio);
    themeVars.navBarBackground = `rgba(255,255,255,${ratio > 1 ? 1 : ratio})`;
  } else if (themeVars.navBarBackground !== 'rgba(255,255,255,1)' || themeVars.navBarTitleTextColor !== 'rgb(0,0,0)') {
    themeVars.navBarBackground = 'rgba(255,255,255,1)';
    setTextColor('rgb(0,0,0)');
  }
}

const title = ref('');
let titleObserver: MutationObserver | null = null;
const setTitle = () => {
  title.value = document.title;
  // 创建一个 MutationObserver 实例并指定回调函数
  titleObserver = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
      if (mutation.type === 'childList') {
        title.value = document.title;
      }
    });
  });
  // 配置 MutationObserver 监听的目标节点以及要观察的变化类型
  titleObserver.observe(document.querySelector('head > title') as Element, {
    childList: true, // 监听子节点变化
  });
};
onMounted(() => {
  // 标题同步设置
  setTitle();
  // 开启顶部渐变模式
  if (props.transparent) {
    if (props.scrollEl) {
      const el = document.querySelector(props.scrollEl);
      if (el) {
        el.addEventListener('scroll', pageScroll);
      }
    } else {
      window.onscroll = pageScroll;
    }
  }
});

onUnmounted(() => {
  titleObserver?.disconnect();
  if (props.scrollEl) {
    const el = document.querySelector(props.scrollEl);
    el?.removeEventListener('scroll', pageScroll);
  }
});
</script>
<template>
  <div class="headerNavBar">
    <van-config-provider :theme-vars="themeVars">
      <van-nav-bar
        z-index="999"
        :title="title"
        :right-text="rightText"
        left-arrow
        :safe-area-inset-top="is_ios()"
        fixed
        :border="!transparent"
        :placeholder="placeholder"
        @click-right="handleClickRight"
        @click-left="handleBack"
      >
        <template #left>
          <van-icon v-if="isFirstPage" size="20" name="cross" />
          <van-icon v-else size="20" name="arrow-left" />
        </template>
      </van-nav-bar>
    </van-config-provider>
  </div>
</template>
<style lang="less" scoped>
.headerNavBar {
  :deep(.van-nav-bar__content),
  :deep(.van-nav-bar__right),
  :deep(.van-nav-bar__left) {
    padding-top: v-bind(statusBarHeight);
  }
}
</style>
